package com.quanyan.place.thread;

import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.TbBizPlaceUnitSalePlan;
import com.quanyan.place.entity.TbBizPlaceUnitSalePlanExample;
import com.quanyan.place.entity.TbBizPlaceUnitSalePlanMain;
import com.quanyan.place.mapper.TbBizPlaceUnitSalePlanMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_COMBINE;

/**
 * Created by yangyun on 16-6-22.
 */
public class SyncSalePlanThread implements Runnable{

    private TbBizPlaceUnitSalePlanMain unitSalePlanMain;

    private TbBizPlaceUnitSalePlanMapper placeUnitSalePlanMapper;

    private int periodWeek;  // 同步销售计划周期

    private Byte unitType;

    private List<Integer> baseUnitIds;

    private Logger logger = LoggerFactory.getLogger(SyncSalePlanThread.class);

    public SyncSalePlanThread(TbBizPlaceUnitSalePlanMain unitSalePlanMain,
                              TbBizPlaceUnitSalePlanMapper placeUnitSalePlanMapper,
                              int periodWeek,
                              Byte unitType,
                              List<Integer> baseUnitIds){
        this.unitSalePlanMain = unitSalePlanMain;
        this.placeUnitSalePlanMapper = placeUnitSalePlanMapper;
        this.periodWeek = periodWeek;
        this.unitType = unitType;
        this.baseUnitIds = baseUnitIds;
    }

    @Override
    public void run() {
        //int periodWeek = PlaceConstants.DEFAULT_PRICE_WEEK_PERIOD;
       /* TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
        criteria.andSalePlanMainIdEqualTo(unitSalePlanMain.getId());
        criteria.andTimeTypeEqualTo(unitSalePlanMain.getTimeType());
        criteria.andIsEffectiveEqualTo(Constants.BYTE_ONE);
        criteria.andStatusEqualTo(PlaceConstants.PLACE_PREORDER_STATUS);
        criteria.andDateGreaterThanOrEqualTo(new Date());
        // 如果已经存在于销售计划表中，更新没有过时的记录
        List<TbBizPlaceUnitSalePlan> salePlanList = placeUnitSalePlanMapper.selectByExample(example);
        for (TbBizPlaceUnitSalePlan salePlan : salePlanList){
            salePlan.setPrice(unitSalePlanMain.getPrice());
            salePlan.setMemberPrice(unitSalePlanMain.getMemberPrice());
            salePlan.setUpdateUid(unitSalePlanMain.getUpdateUid());
            salePlan.setUpdateTime(Calendar.getInstance().getTime());
            placeUnitSalePlanMapper.updateByPrimaryKey(salePlan);
        }*/

        // 按指定周期同步新增的部分
        Integer dayOfWeek = transferDayOfWeek(unitSalePlanMain.getTimeType());
        Calendar nowDate =  Calendar.getInstance(); // 当前日期
        String hour = DateTimeUtils.convertDate2String("HH", unitSalePlanMain.getStartTime());

        for (int i=0; i<=periodWeek; i++){
            Calendar calendar = Calendar.getInstance(Locale.CHINA);
            calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
            calendar.add(Calendar.DAY_OF_WEEK, 7 * i);
            // n小时之前场地价格不可修改
            int pricingInAdvanceHour = 0; // TODO
            if (!isCanPricing(nowDate.getTime(), calendar.getTime(), pricingInAdvanceHour)){
                // 指定时间之前不能定价
                continue;
            }
            TbBizPlaceUnitSalePlan salePlan = new TbBizPlaceUnitSalePlan();
            salePlan.setDate(calendar.getTime());
            salePlan.setSaleId(CommonUtils.createSaleID(unitSalePlanMain.getPlaceUnitId(), calendar.getTime(),
                    unitSalePlanMain.getStartTime(), unitSalePlanMain.getEndTime())); // 销售计划Id
            salePlan.setSalePlanMainId(unitSalePlanMain.getId());
            salePlan.setStatus(Constants.BYTE_ONE);
            salePlan.setIsEffective(Constants.BYTE_ONE);
            salePlan.setCategoryId(unitSalePlanMain.getCategoryId());
            salePlan.setTimeType(unitSalePlanMain.getTimeType());
            salePlan.setPlaceId(unitSalePlanMain.getPlaceId());
            salePlan.setPlaceUnitId(unitSalePlanMain.getPlaceUnitId());
            salePlan.setPlaceUnitName(unitSalePlanMain.getPlaceUnitName());
            salePlan.setPrice(unitSalePlanMain.getPrice());
            salePlan.setMemberPrice(unitSalePlanMain.getMemberPrice());
            salePlan.setPlaceId(unitSalePlanMain.getPlaceId());
            salePlan.setStartTime(unitSalePlanMain.getStartTime());
            salePlan.setEndTime(unitSalePlanMain.getEndTime());
            salePlan.setVersion(unitSalePlanMain.getVersion());
            salePlan.setCreateUid(unitSalePlanMain.getCreateUid());
            salePlan.setCreateTime(Calendar.getInstance().getTime());
            salePlan.setUpdateUid(unitSalePlanMain.getUpdateUid());
            salePlan.setUpdateTime(Calendar.getInstance().getTime());
            if (unitSalePlanMain.getBundleNo() != null){
                if (unitSalePlanMain.getBundleNo() == 0){
                    salePlan.setBundleNo(0);
                } else {
                    String bundleNo = unitSalePlanMain.getPlaceUnitId()+""+unitSalePlanMain.getBundleNo();
                    salePlan.setBundleNo(Integer.valueOf(bundleNo));
                }
            }


            // 如果是组合场,记录子场销售计划
            salePlan.setUnitType(this.unitType);
            if (UNIT_TYPE_COMBINE.equals(this.unitType)) {
                if (this.baseUnitIds == null || this.baseUnitIds.size() <= 0) {
                    logger.info("非法的组合销售计划,baseUnitIds为空, mainId：{} startTime:{}", unitSalePlanMain.getId(), unitSalePlanMain.getStartTime());
                    continue;
                }

                List<String> saleIds = new ArrayList<>();
                for (Integer buId : this.baseUnitIds) {
                    saleIds.add(CommonUtils.createSaleID(buId, calendar.getTime(),
                            unitSalePlanMain.getStartTime(), unitSalePlanMain.getEndTime()));
                }
                salePlan.setSubSaleplans(StringUtil.join("|", saleIds));
            }

            try {
                System.out.println("=====================================>salePlan.getId():"+salePlan.getSaleId());
                //加入增加的销售计划id
                placeUnitSalePlanMapper.insert(salePlan);
            } catch (Exception e) {
                if (unitSalePlanMain.getIsEffective() == PlaceConstants.YES){
                    TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
                    TbBizPlaceUnitSalePlanExample.Criteria tbBizPlaceUnitSalePlanCriteria = tbBizPlaceUnitSalePlanExample.createCriteria();
                    tbBizPlaceUnitSalePlanCriteria.andPlaceIdEqualTo(unitSalePlanMain.getPlaceId());
                    tbBizPlaceUnitSalePlanCriteria.andPlaceUnitIdEqualTo(unitSalePlanMain.getPlaceUnitId());
                    tbBizPlaceUnitSalePlanCriteria.andSaleIdEqualTo(CommonUtils.createSaleID(unitSalePlanMain.getPlaceUnitId(),
                            calendar.getTime(), unitSalePlanMain.getStartTime(), unitSalePlanMain.getEndTime()));
                    tbBizPlaceUnitSalePlanCriteria.andCategoryIdEqualTo(unitSalePlanMain.getCategoryId());
                    tbBizPlaceUnitSalePlanCriteria.andTimeTypeEqualTo(unitSalePlanMain.getTimeType());
                    tbBizPlaceUnitSalePlanCriteria.andStartTimeEqualTo(unitSalePlanMain.getStartTime());
                    tbBizPlaceUnitSalePlanCriteria.andEndTimeEqualTo(unitSalePlanMain.getEndTime());
                    List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = placeUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample);
                    if (!tbBizPlaceUnitSalePlanList.isEmpty()){
                        //没有定出去的场地才允许重新定价
                        if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceUnitSalePlanList.get(0).getStatus())){
                            if (tbBizPlaceUnitSalePlanList.get(0).getStatus() == 1
                                    || tbBizPlaceUnitSalePlanList.get(0).getStatus() == 4){
                                tbBizPlaceUnitSalePlanList.get(0).setVersion(unitSalePlanMain.getVersion());
                                tbBizPlaceUnitSalePlanList.get(0).setIsEffective(Constants.BYTE_ONE);
                                //价格变更
                                tbBizPlaceUnitSalePlanList.get(0).setPrice(unitSalePlanMain.getPrice());
                                tbBizPlaceUnitSalePlanList.get(0).setMemberPrice(unitSalePlanMain.getMemberPrice());
                                placeUnitSalePlanMapper.updateByPrimaryKeySelective(tbBizPlaceUnitSalePlanList.get(0));
                            }
                        }
                    }
                }else{
                    logger.info("销售计划同步失败:mainId：{} startTime:{}", unitSalePlanMain.getId(), unitSalePlanMain.getStartTime());
                }
            }
        }
    }

    /**
     * 将数据库保存的星期表示数转换为适用于日历的整数
     * @param timeType
     * @return
     */
    private Integer transferDayOfWeek(String timeType) {
        Integer dayOfWeek = 0;
        if (StringUtils.isNotEmpty(timeType)){
            dayOfWeek = Integer.valueOf(timeType); // 星期：1,2,3....7
            if (null != dayOfWeek){
                // 因为DAY_OF_WEEK 星期日为一周的第一天，赋值时做一次转换
                if (dayOfWeek == 7){
                    dayOfWeek = 1;
                } else if (dayOfWeek < 7){
                    dayOfWeek = dayOfWeek +1;
                }
            }
        }
        return dayOfWeek;
    }

    /**
     * 判断指定销售计划时间是否能变更价格
     * @param fromTime
     * @param toTime
     * @param pricingInAdvanceHour
     * @return
     */
    private boolean isCanPricing(Date fromTime, Date toTime, int pricingInAdvanceHour) {
        int periodHour = DateUtils.dateDiffHour(fromTime, toTime);
        return periodHour >= pricingInAdvanceHour;
    }

    public static String createID() {
        UUID randomUUID = UUID.randomUUID();
        String uuid = randomUUID.toString().replaceAll("-", "");
        StringBuffer bf = new StringBuffer();
        bf.append(uuid);
        return bf.toString().toLowerCase();
    }
}
